package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    //这里的token不完整，所以可以用获取token后拼接
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;


    @Override
    public String getOpenId(String code) {
        Map<String, Object> params = getCommonParams();
        params.put("js_code",code);

        String result = HttpUtil.get(REQUEST_URL,params);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException("错误码:" + jsonObject.getInt("errcode") + "错误信息:" + jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String code) {
        Map<String, Object> params = new HashMap<>();
        String token = getToken();
        params.put("code",code);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token,JSONUtil.toJsonStr(params));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0){
            throw new RuntimeException("错误码:" + jsonObject.getInt("errcode") + "错误信息:" + jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }

    /**
     * 获取公共参数
     * @return
     */
    private Map<String,Object> getCommonParams(){
        //appId和secret是重复字段，所以可以封装成一个方法反复调用
        Map<String,Object> requestUrlParams = new HashMap<>();
        requestUrlParams.put("appId",appId);
        requestUrlParams.put("secret",secret);
        return requestUrlParams;
    }

    private String getToken(){
        Map<String, Object> params = getCommonParams();
        String result = HttpUtil.get(TOKEN_URL, params);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException("错误码:" + jsonObject.getInt("errcode") + "错误信息:" + jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
